package game.players.goalkeeper;

import game.ball.Free;
import game.ball.Possessed;
import game.ball.SoccerBall;
import game.players.SoccerPlayer;
import game.players.goalkeeper.mate.GoalkeeperWithoutBallMate;
import game.players.goalkeeper.opp.GoalkeeperWithoutBallOpp;

import com.uqbar.vainilla.DeltaState;
import com.uqbar.vainilla.appearances.Appearance;

public class FlyingGoalkeeper extends GoalkeeperState {
	
	private int flyingSpeed;
	private int lifeTime  = 10;
	private boolean catchTheBall = false;
	private SoccerBall ball;
	private boolean rebound = false;//necesario para que rebote una sola vez
	private Appearance stationarySprite;

	public FlyingGoalkeeper(SoccerPlayer goalkeeper) {
		super(goalkeeper);
		this.ball = this.getGoalkeeper().getScene().getSoccerBall();
		this.stationarySprite = goalkeeper.getAppearance(); 
	}

	@Override
	public void update(DeltaState deltaState) {
		if(this.lifeTime==0){
			this.getGoalkeeper().setAppearance(this.stationarySprite);//luego de tirarse se pone de pie
			if(this.catchTheBall){
				this.getGoalkeeper().takeTheBall();
			}
			else
				if(this.getGoalkeeper().isUserMate())
					this.getGoalkeeper().setState(new GoalkeeperWithoutBallMate(this.getGoalkeeper()));
				else
					this.getGoalkeeper().setState(new GoalkeeperWithoutBallOpp(this.getGoalkeeper()));
		}else{			
			if(!this.catchTheBall && !this.rebound){
				this.getGoalkeeper().move(0,this.flyingSpeed);
				if(this.collidesAgainstBall()){
					if (this.ball.isFree()) {
						if(((Free)this.ball.getState()).getSpeed()<=5){//si la velocidad de la pelota es <=5 no da rebote
							ball.setState(new Possessed(this.getGoalkeeper()));
							this.catchTheBall = true;
						}else
							this.rebound((Free) this.ball.getState());						
					}else{//la pelota no estaba libre
						this.ball.getPlayer().loseTheBall();
						ball.setState(new Possessed(this.getGoalkeeper()));
						this.catchTheBall = true;
					}
				}
			}else{
				if(this.catchTheBall)
					this.ball.moveNormally(0,this.flyingSpeed);
			}				
			this.lifeTime--;			
		}
	}

	public void rebound(Free ballState) {
		ballState.setVersorI(-ballState.getVersorI());
		// Le quita un 50% de velocidad
		double speedToExtract = ballState.getSpeed() * 50 / 100;
		ballState.setSpeed(ballState.getSpeed() - speedToExtract);
		this.rebound=true;
		this.ball.setLastTouched(this.getGoalkeeper());
	}

	@Override
	public boolean isWithBall() {
		return this.catchTheBall;
	}

	@Override
	public boolean isRight() {
		return false;
	}
	
	public void setFlyingSpeed(int flyingSpeed) {
		this.flyingSpeed = flyingSpeed;
	}

}
